﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Web.Mvc;

namespace WeBlog.Core {
	public static class RecaptchaUtils {
		public static JsonResult ValidateRecaptcha( string privateKey, string remoteip, string challenge, string response) {
			string postData = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
													  privateKey, remoteip,
													  challenge, response);
			JsonResult result = new JsonResult();
			byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);

			Uri serviceUri = new Uri("http://api-verify.recaptcha.net/verify", UriKind.Absolute);
			try {
				HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
				webRequest.ContentType = "application/x-www-form-urlencoded";
				webRequest.ContentLength = postDataBuffer.Length;
				webRequest.Method = "POST";
				
				//incase you are using a proxy server
				IWebProxy proxy = WebRequest.GetSystemWebProxy();
				proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
				webRequest.Proxy = proxy;

				Stream requestStream = webRequest.GetRequestStream();
				requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);

				HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
				string jsonResponse = string.Empty;

				using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
					jsonResponse = sr.ReadToEnd();

				string[] tokens = jsonResponse.Split(new char[] { '\n' });
				if (tokens.Length == 2) {
					Boolean success = tokens[0].Equals("true", StringComparison.CurrentCulture);
					result.Data = new { Success = success, Message = tokens[1] };
				}
				else {
					result.Data = new { Success = false, Message = "Invalid response returned" };
				}
			}
			catch (Exception ex) {
				result.Data = new { Success = false, Message = ex.Message };
			}

			return result;
		}
	}
}